// 导入基础库
import React, { useEffect } from 'react'
import { connect } from 'umi'
// 导入处理函数
import { setClassName, drop, reset_tags } from '../methods'
// 导入UI组件
import { Button, Divider } from 'antd';
import css from './tags.less'


// 单个标签组件
const Tag = props => {
    const { tag } = props

    const tag_methods = {
        onDragStart: e => {
            e.dataTransfer.setData("Text", e.target.id)
        },
        onDrag: e => {
            e.target.className = css.tag_drag
        },
        onDragEnd: e => {
            e.target.className = css.tag
        }
    }

    return (
        <div id={tag} className={css.tag} draggable {...tag_methods}>{tag}</div>
    )
}

const TableDrop = props => {
    const { tag, dispatch, state } = props

    const tag_methods = {
        onDrop: e => {
            setClassName(e.target, 'table_drop_box', css.table_drop_box)
            drop(e, tag.multi, dispatch, state)
        },
        onDragOver: e => {
            setClassName(e.target, 'table_drop_box', css.table_drop_box_over)
        },
        onDragLeave: e => {
            setClassName(e.target, 'table_drop_box', css.table_drop_box)
        }
    }

    return (
        <div className={css.table_tag}>
            <p>{tag.title} <span>{state.tag_bind[tag.key].length}/{tag.multi}</span></p>
            <div id={tag.key} className={css.table_drop_box} {...tag_methods}>
                {state.tag_bind[tag.key].map((t, tid) =>
                    <Tag key={tid} tag={t} />
                )}
            </div>
        </div>
    )
}

// 标签关联组件
const tags = (props) => {
    const { global: state, dispatch, onSave } = props;

    // 禁用默认事件
    useEffect(() => {
        document.addEventListener('drop', e => e.preventDefault(), false)
        document.addEventListener('dragover', e => e.preventDefault(), false)
    })

    const reset = () => reset_tags(state, dispatch)

    const save = () => {
        onSave(state, dispatch)
    }

    return (
        <div className={css.tags_box}>
            <div className={css.btn}>
                <Button onClick={reset}>重置</Button>
                <Divider type="vertical" />
                <Button disabled={state.tag_bind.xm.length === 0 ? true : state.tag_bind.sfz.length === 0 ? true : false} type="primary" onClick={save}>保存表头标签，进入下一步</Button>
            </div>

            <div id={css.file_tags} className={css.file_tags} onDrop={e => drop(e, 100, dispatch, state)}>
                {state.file_data_cols.map((tag, tid) =>
                    <Tag key={tid} tag={tag} />
                )}
            </div>
            <div className={css.table_tags}>
                {state.table_cols.map((tag, tid) =>
                    <TableDrop key={tid} tag={tag} dispatch={dispatch} state={state} />
                )}
            </div>
        </div>
    )
}

export default connect(({ global }) => ({ global }))(tags)